package com.cloud.platform.util;

import java.util.List;

import com.cloud.platform.IDao;

public class SnUtil {

	/**
	 * get sn
	 * 
	 * @param module
	 * @param snid
	 * @return
	 */
	public static int getSn(String module, String snid, String belongName, String belongId) {
		
		IDao dao = SpringUtil.getDao();
		
		int sn = 1;
		List list = null;
		StringBuffer hql = new StringBuffer();
		
		// if snid is null or empty, get max sn
		if(StringUtil.isNullOrEmpty(snid)) {
			hql.append("select max(sn) from " + module);
			
			if(!StringUtil.isNullOrEmpty(belongName)) {
				hql.append(" where " + belongName + " = '" + belongId + "'");
			}
			
			list = dao.getAllByHql(hql.toString());
			
			if(list != null && !list.isEmpty() && list.get(0) != null) {
				sn = (Integer) list.get(0) + 1;
			}
		}
		// if snid is not empty, get sn by previous record sn
		else if(snid.length() == 36) {
			// get previous record sn
			hql.append("select sn from " + module + " where id = '" + snid + "'");
			list = dao.getAllByHql(hql.toString());

			if(list != null && !list.isEmpty()) {
				sn = (Integer) list.get(0) + 1;
				
				// update records' sn plus 1 that sns bigger that the previous record sn
				hql.setLength(0);
				hql.append("update " + module + " set sn = sn + 1 where sn >= " + sn);
				
				if(!StringUtil.isNullOrEmpty(belongName)) {
					hql.append(" and " + belongName + " = '" + belongId + "'");
				}
				
				dao.updateByHql(hql.toString());
			}
		}
		
		return sn;
	}
}
